# -*-coding:utf-8 -*-
import re 
import base64
from obs import ObsClient

OBS_ENDPOINT_DICT = {
    "cn-north-7" : "https://obs.{region}.ulanqab.huawei.com"
}
OBS_DEFALUT_ENDPOINT = "https://obs.{region}.myhuaweicloud.com"

LASR_ENDPOINT_DICT = {
    "cn-north-7" : "https://99e33763f1084f2cb68e2d0dcd3ed27a.apigw.cn-north-7.myhuaweicloud.com/v1/{project_id}/asr/transcriber/jobs",

}
LASR_DEFAULT_ENDPOINT = "https://sis-ext.{region}.myhuaweicloud.com/v1/{project_id}/asr/transcriber/jobs"



def build_obs_client(context, region) :
    """ 创建obs_client实例
    :param context: 上下文信息
    :param region: obs桶所在区域，可在环境变量中指定
    :return: 实例化的obs_client
    """
    endpoint = OBS_ENDPOINT_DICT.get(region, None)
    if endpoint is None :
        endpoint = OBS_DEFALUT_ENDPOINT

    ak = context.getAccessKey()
    sk = context.getSecretKey()

    server_url = endpoint.replace("{region}", str(region))
    print(server_url)

    return ObsClient(access_key_id=ak, secret_access_key=sk, server=server_url, path_style=False,
                    ssl_verify=False, max_retry_count=5, timeout=20)


def download_file_from_obs(obs_client, bucket_name, object_name, local_object_path) :
    """ 从obs下载对象
    :param obs_client: obs客户端实例
    :param bucket_name: obs桶名称
    :param object_name: 对象名称
    :param local_object_path: 将对象保存到的本地路径
    """
    try :
        resp = obs_client.getObject(bucket_name, object_name, local_object_path)
        print(resp)
        if resp.status < 300 :
            print('Download {} succeed.'.format(object_name))
        else :
            raise Exception('Download failed, error code: {}, error message: {}'.format(
                resp.errorCode, resp.errorMessage))
    except Exception as e :
        raise Exception(e)


def upload_file_to_obs(obs_client, bucket_name, object_name, data_file) :
    """ 上传对象到obs
    :param obs_client: obs客户端实例
    :param bucket_name: obs桶名称
    :param object_name: 对象名称
    :param data_file: 数据对象
    """
    resp = obs_client.putContent(bucket_name, object_name, data_file)
    if resp.status < 300 :
        print('Upload {} succeed.'.format(object_name))
    else :
        raise Exception('Upload failed, error code: {}, error message: {}'.format(
            resp.errorCode, resp.errorMessage))

def get_data_url(region, bucket_name, object_name):
    endpoint = OBS_ENDPOINT_DICT.get(region, None)
    if endpoint is None :
        endpoint = OBS_DEFALUT_ENDPOINT
    endpoint = endpoint.replace("{region}", str(region))
    data_url = endpoint.split("//")[0]+"//"+ bucket_name +"."+ endpoint.split("//")[1] + "/"+object_name
    print(data_url)
    return data_url 




def get_post_url(context, region) :
    """获取post的url
    """
    post_url = LASR_ENDPOINT_DICT.get(region, None)
    if post_url is None :
        post_url = LASR_DEFAULT_ENDPOINT.replace("{region}", str(region))
    return post_url.replace("{project_id}", str(context.getProjectID()))


def get_headers(context) :
    """ 获取post的headers
    """
    token = context.getToken()
    headers = {
        "x-auth-token" : token,
        "content-type" : 'application/json'
    }
    return headers


def get_norm_result(event, json_data) :
    """ 获取同步工作流的标准输出结果
    """
    result = {
        "execution_name" : event.get("execution_name", ""),
        "graph_name" : event.get("graph_name", ""),
        "Records" : event.get("Records", []),
        "dynamic_source" : {
            "tasks" : [json_data]
        }
    }
    return result
